/*
 * ProxyApplication.h
 *
 *  Created on: 2013-12-19
 *      Author: lixingyi
 */

#ifndef PROXY_APPLICATION_H_
#define PROXY_APPLICATION_H_

#include <map>
#include <set>
#include <vector>
#include <memory>
#include <unordered_map>
#include <atomic>

#include "framework/day_roll_logger.h"
#include "framework/application.h"
#include "framework/tcp_acceptor.h"

class ProxyThread ;
class MysqlThread ;
class LogThread ;

class ClientAcceptor : public kingnet::tcp_acceptor
{
public:
    ClientAcceptor() ;
    int on_connection(int fd,kingnet::sa_in_t* addr) ;

public:
    std::unordered_map<int,std::shared_ptr<ProxyThread> > proxy_thread_container ;
    
};

typedef std::unordered_map<int,std::shared_ptr<MysqlThread> > MysqlThreadContainer ;

class MysqlThreadManager
{
public:
    ~MysqlThreadManager() { fini();} ;

    int init(const char* config_file) ;

    bool is_all_running() ;

    void fini() ;

    MysqlThread* get_mysql_thread(int id);

private:
    MysqlThreadContainer m_thread_container ;
    MysqlThread* m_default_thread ;

} ;


class ProxyApplication : public kingnet::application
{
public:
    ProxyApplication();
    virtual ~ProxyApplication();

public:
    MysqlThread* get_mysql_thread(int id);
    LogThread* log_thread() { return m_log_thread.get();} ;
protected:
    virtual int on_init() ;
    virtual int on_reload() ;
    virtual void on_fini() ;
    virtual void on_timer() ;
    virtual const char* version()  ;
	virtual void on_delay_stop();


public:
    kingnet::day_roll_logger logger ;

private:
    ClientAcceptor  m_client_acceptor ;
    std::atomic<MysqlThreadManager*> m_mysql_manager ;
    std::map<int64_t,MysqlThreadManager*> m_delayed_manager ;
    std::shared_ptr<LogThread> m_log_thread ;

	bool m_is_shuting_down;

};

DECLARE_APPLICATION_INSTANCE(ProxyApplication) ;

#endif /* PROXY_APPLICATION_H_ */
